import type { Request, Response } from 'express';

import axios from 'axios';
import {
  responseError,
  responseSuccess,
} from '@/share/interface/standard';
import Base from '@/controller/public/MiniBaseController';

const { exec } = require('child_process');
const tencentcloud = require('tencentcloud-sdk-nodejs');
const clientId = 'GHOU6cLrdsO6SnzeoBWVHhQy';
const clientSecret = 'QWrA6w5m9jrlZh2GmVlXA73jXftJMNgH';
const path = 'https://aip.baidubce.com/oauth/2.0/token';

/* eid 部分 */
const MerchantId = '0NSJ2409241111580316';
const clientConfig = {
  credential: {
    secretId: 'AKIDgSNDwXDqS8qbZcdeWRLHHMYh1VxJ9124',
    secretKey: '558Sl9fH5rbHuSygSPNKFA4vtocFcG2l',
  },
  region: '',
  profile: {
    httpProfile: {
      endpoint: 'faceid.tencentcloudapi.com',
    },
  },
};

const FaceidClient = tencentcloud.faceid.v20180301.Client;
const client = new FaceidClient(clientConfig);

export class OcrController extends Base {
  async customOcr(req: Request, res: Response) {
    const { image } = req.body;
    try {
      const tokenResponse = await axios.get(
        `${path}?client_id=${clientId}&client_secret=${clientSecret}&grant_type=client_credentials`
      );
      const accessToken = tokenResponse.data.access_token;

      const ocrUrl =
        'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' +
        accessToken;

      const ocrResponse = await axios({
        method: 'post',
        url: ocrUrl,
        data: `image=${encodeURIComponent(image)}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Accept: 'application/json',
        },
      });
      res.json(ocrResponse.data);
    } catch (error) {
      console.error(error);
      res.status(500).send('Error processing OCR');
    }
  }
  async getOcr(req: Request, res: Response) {
    const { image, id_card_side, url } = req.body;
    try {
      const tokenResponse = await axios.get(
        `${path}?client_id=${clientId}&client_secret=${clientSecret}&grant_type=client_credentials`
      );
      const accessToken = tokenResponse.data.access_token;

      const ocrUrl =
        'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' +
        accessToken;

      const ocrResponse = await axios({
        method: 'post',
        url: ocrUrl,
        data: `image=${encodeURIComponent(image)}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Accept: 'application/json',
        },
        params: {
          id_card_side,
          url,
          detect_ps: 'false',
          detect_risk: 'false',
          detect_quality: 'false',
          detect_photo: 'false',
          detect_card: 'false',
          detect_direction: 'false',
        },
      });
      res.json(ocrResponse.data);
    } catch (error) {
      console.error(error);
      res.status(500).send('Error processing OCR');
    }
  }

  async getOcrForVehicleLicense(req: Request, res: Response) {
    const { image, side, url } = req.body;

    try {
      const tokenResponse = await axios.get(
        `${path}?client_id=${clientId}&client_secret=${clientSecret}&grant_type=client_credentials`
      );
      const accessToken = tokenResponse.data.access_token;

      const ocrUrl =
        'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=' +
        accessToken;

      const ocrResponse = await axios({
        method: 'post',
        url: ocrUrl,
        data: `image=${encodeURIComponent(image)}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Accept: 'application/json',
        },
        params: {
          url,
          vehicle_license_side: side,
          detect_ps: 'false',
          detect_risk: 'false',
          detect_quality: 'false',
          detect_photo: 'false',
          detect_card: 'false',
          detect_direction: 'false',
        },
      });
      res.json(ocrResponse.data);
    } catch (error) {
      console.error(error);
      res.status(500).send('Error processing OCR');
    }
  }

  async webHook(req: Request, res: Response) {
    // 执行同步命令
    exec(
      'cd /data/nginx/typerom-chf && git fetch --all && git reset --hard origin/main && git reset  && pm2 restart orm',
      (err, stdout, stderr) => {
        if (err) {
          console.error(`exec error: ${err}`);
          return;
        }
        console.log(`stdout: ${stdout}`);
        console.error(`stderr: ${stderr}`);
      }
    );

    res.status(200).json({
      message: 'Webhook received and processed',
    });
  }
  async convertTextToSpeech(req: Request) {
    const { text } = req.body;
    async function getAccessToken() {
      const AK = 'ddOrPGCO7yWMx1GLFk0P8VYu';
      const SK = 'wGsDLTQBLzUP4SJwnQiaWdDlhNqEq7v2';
      try {
        const response = await axios({
          method: 'post',
          url: 'https://aip.baidubce.com/oauth/2.0/token',
          data: {
            grant_type: 'client_credentials',
            client_id: AK,
            client_secret: SK,
          },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Accept: 'application/json',
          },
        });
        console.log(response.data.access_token, 'response');
        return response.data.access_token;
      } catch (error) {
        console.error('Failed to get access token:', error.message);
      }
    }

    try {
      const queryParams = {
        tex: text,
        tok: await getAccessToken(),
        cuid: 'MmjxWIr1T0dfSSIlCMpxaVgkY0mkbXwJ',
        ctp: '1',
        lan: 'zh',
        spd: '5',
        pit: '5',
        vol: '5',
        per: '1',
        aue: '3',
      };

      // 手动构建查询字符串
      const queryString = Object.keys(queryParams)
        .map(
          (key) =>
            `${encodeURIComponent(key)}=${encodeURIComponent(
              queryParams[key]
            )}`
        )
        .join('&');

      const url = `https://tsn.baidu.com/text2audio?${queryString}`;

      const response = await axios({
        url: url,
        method: 'GET',
        responseType: 'arraybuffer', // 指定响应类型为 arraybuffer
        headers: {
          'Content-Type': 'audio/mp3',
          Accept: '*/*',
        },
      });

      // 假设response[1].data是base64字符串
      // const audioBase64 = response[1].data;
      // // 使用uni.base64ToArrayBuffer将base64字符串转换为ArrayBuffer
      // const arrayBuffer = uni.base64ToArrayBuffer(audioBase64);
      // console.log(arrayBuffer, "audioBase64")

      // 创建Blob对象
      // const blob = new Blob([arrayBuffer], { type: 'audio/mp3' });
      // console.log(blob,"blob")
      // 创建音频URL
      // const audioURL = URL.createObjectURL(blob);
      //
      const buffer = Buffer.from(response.data);
      const audioBase64 = buffer.toString('base64');

      // 播放音频
      return responseSuccess(audioBase64);
    } catch (error) {
      console.error('Error:', error.message);
    }
  }

  // 获取E通证Token
  async getEidToken(req: Request) {
    const { IdCard, Name } = req.body;

    try {
      const eid_token = await client.GetEidToken({
        MerchantId,
        IdCard,
        Name,
        InputType: 4,
      });
      const { EidToken, RequestId, Url } = eid_token;
      // req.session.eid_token = EidToken;
      if (!RequestId) {
        return responseError('未知错误，请联系管理员');
      }
      return responseSuccess({ EidToken, Url });
    } catch (err) {
      return responseError(err.message);
    }
  }

  // 获取E证通结果信息
  async getEidResult(req: Request) {
    const { eidToken } = req.body;
    const eid_result = await client.GetEidResult({
      EidToken: eidToken,
    });

    if (!eid_result.RequestId)
      return responseError('未知错误，请联系管理员');

    // req.session.eid_token = '';
    return responseSuccess(eid_result);
  }

  // 获取SDKToken
  async getSdkToken(req: Request) {
    const { IdCard, Name } = req.body;
    if (!IdCard || !Name)
      return responseError('IdCard或Name不能为空');
    const { FaceIdToken, RequestId } = await client.GetFaceIdToken({
      CompareLib: 'BUSINESS',
      IdCard,
      Name,
    });
    if (!RequestId) return responseError('未知错误，请联系管理员');

    req.session.face_id_token = FaceIdToken;
    return responseSuccess(FaceIdToken);
  }

  // 获取SDK核验结果
  async getSdkResult(req: Request) {
    const face_result = await client.GetFaceIdResult({
      FaceIdToken: req.session.face_id_token,
    });
    if (!face_result.RequestId)
      return responseError('未知错误，请联系管理员');
    // req.session.face_id_token = '';
    return responseSuccess(face_result);
  }

  // 保存数据
  async saveData(req: Request) {
    const { json_data } = req.body;
    await this.dataRepository.save({
      id: 1,
      json_data,
    });

    // 保存数据
    return responseSuccess();
  }

  async getData() {
    const data = await this.dataRepository.find({
      where: { id: 1 },
    });
    return responseSuccess(data);
  }
}
